package com.cblue.qimokao.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.cblue.qimokao.entity.Film;
import com.cblue.qimokao.service.FilmService;
import com.cblue.qimokao.vo.PageResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * yaosenyv
 * sen
 */
@RestController
@RequestMapping("/doctor")
public class FilmController {

    @Resource
    private FilmService doctorService;


    @RequestMapping("/findByPage")
    public PageResult findByPage(@RequestBody Map<String,Object> searchMap, Integer page, Integer size){
        return doctorService.findByPage(searchMap,page,size);
    }

    @RequestMapping("/export")
    public void export(HttpServletRequest request, HttpServletResponse response)throws Exception{
        //获得数据
        List<Film> list = doctorService.findAll();

        //设置导出的响应头属性
        setExcelRespProp(response,"电影信息");
        //对文件对象
        EasyExcel.write(response.getOutputStream())
                .head(Film.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("电影列表")
                .doWrite(list);

    }

    /**
     * 设置excel下载响应头属性
     */
    private void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        //设置相应的内容类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //设置相应的编码
        response.setCharacterEncoding("utf-8");
        //获得文件名（进行一个编码，防止乱码）
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("/+", "%20");
        //设置返回的相应头（返回方式：以附件，文件名）
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }

}
